<template>
    <xh-pages :tabBar="true">
        <view class="user-container">
            <!-- 信息块 -->
            <view class="user-bg-container">
                <view class="info-block">
                    <!-- 个人信息 -->
                    <view class="user-box">
                        <view class="userinfo" @tap="openWin({ url: '/pages/users/personal/index' })">
                            <view class="avatar-box">
                                <image class="avatar" :src="userInfo.avatar"></image>
                                <view class="is-level" v-if="userInfo.is_vip">
                                    <view class="level-icon">VIP</view>
                                </view>
                            </view>
                            <view class="info">
                                <view class="nickname">{{ userInfo.nickname }}</view>
                                <view class="level">
                                    <u-icon name="level" color="#E7A33D"></u-icon>
                                    <text>
                                        {{ userInfo.is_vip ? `到期时间：${userInfo?.vip_expire_time}` : '非会员用户' }}
                                    </text>
                                </view>
                            </view>
                        </view>
                    </view>
                    <!-- 账户财务 -->
                    <view class="user-account-cash">
                        <view class="item">
                            <view class="num">{{ userInfo.team_sum }}</view>
                            <view class="text">邀请人数</view>
                        </view>
                        <view class="item">
                            <view class="num">￥{{ userInfo.amount }}</view>
                            <view class="text">订单总额</view>
                        </view>
                        <view class="item">
                            <view class="num">￥{{ userInfo.amount_total }}</view>
                            <view class="text">累计收益</view>
                        </view>
                    </view>
                </view>
            </view>
            <!-- 代理入口 -->
            <view class="dealer-container" v-if="['10', '30', '40'].includes(siteInfo.dealer_apply)">
                <view class="text-container">
                    <u-icon name="/static/icon_zhuan_my@2x.png" size="32"></u-icon>
                    <view class="text">
                        成为代理，
                        <text class="warning">躺赚收益！</text>
                    </view>
                </view>
                <view class="apply-btn" @tap="openWin({ url: '/pages/users/dealer/index' })">
                    立即申请
                </view>
            </view>
            <view class="dealer-container" v-if="siteInfo.dealer_apply === '20'">
                <view class="text-container">
                    <u-icon name="/static/icon_zhuan_my@2x.png" size="32"></u-icon>
                    <view class="text">
                        欢迎回来
                        <text class="warning">{{ userInfo.nickname }}</text>
                    </view>
                </view>
                <view class="apply-btn" @tap="openWin({ url: '/pages/users/dealer/index' })">
                    分销中心
                </view>
            </view>
            <!-- 服务工具 / 会员特权 -->
            <view class="service-container" :class="{ 'dealer-close': siteInfo.dealer?.dealer_status === '10' }">
                <u-tabs :current="serviceTools.current" :list="serviceTools.list" @click="handleTabs" lineColor="#17181B" />
                <view class="tools-container" v-if="serviceTools.active === 'service'">
                    <view class="item" v-for="(item, index) in tools" :key="index" @tap="openWin({ url: item.path })">
                        <u-icon :name="item.icon" size="22" color="#333333"></u-icon>
                        <view class="text">{{ item.text }}</view>
                    </view>
                </view>
                <view class="vip-container" v-if="serviceTools.active === 'vip'">
                    <view class="divider">
                        <u-divider text="开通会员" textColor="#612816" lineColor="#f0ad4e" />
                    </view>
                    <view class="desc-vip">
                        {{ siteInfo.vip_desc ? siteInfo.vip_desc : '会员有效期为一个月，解锁会员可以获得以下特权' }}
                    </view>
                    <view class="privilege-vip">
                        <view class="item" v-for="(item, index) in privilege" :key="index">
                            <u-icon :name="item.icon" size="50"></u-icon>
                            <view class="text">{{ item.text }}</view>
                        </view>
                    </view>
                    <view class="unlock-vip">
                        <view class="unlock-btn" @tap="hanldPay" v-if="userInfo.is_vip && siteInfo.vip_renew_money">
                            我要续费
                        </view>
                        <view class="unlock-btn" v-else @tap="hanldPay">
                            ￥{{ siteInfo.vip_buy_money }}我要解锁
                        </view>
                    </view>
                </view>
            </view>
        </view>
    </xh-pages>
</template>

<script setup lang="ts">
import { useSite } from '@/stores/site';
import { useUserStore } from '@/stores/user';
import { isWeiXinLogin, openWin, toast } from '@/utils/helpers';

const siteInfo = storeToRefs(useSite()).siteInfo
const userInfo = storeToRefs(useUserStore()).userInfo
const payInfo = ref();
const orderNo = ref('')
const OrderStateNum = ref(1);

const serviceTools = ref({
    active: 'service',
    current: 0,
    list: [{
        name: '服务工具',
        type: 'service',
    }, {
        name: '会员特权',
        type: 'vip',
    }]
})
const tools = ref([
    {
        icon: 'rmb-circle',
        text: '我的钱包',
        path: '/pages/users/wallet/index',
    },
    {
        icon: 'email',
        text: '意见反馈',
        path: '/pages/users/report/index',
    },
    {
        icon: 'question-circle',
        text: '关于我们',
        path: '#tags?name=system_about',
    },
])
const privilege = ref([
    {
        icon: '/static/vip/icon_mate_vip@2x.png',
        text: '无限匹配',
    },
    {
        icon: '/static/vip/icon_record_vip@2x.png',
        text: '全部记录',
    },
    {
        icon: '/static/vip/icon_effect_vip@2x.png',
        text: '更多特效',
    },
    {
        icon: '/static/vip/icon_ok_vip@2x.png',
        text: '匹配成功率',
    },
])

const handleTabs = (e: any) => {
    const type = e?.type ?? ''
    if (!type) {
        toast('类型错误');
        return;
    }
    serviceTools.value.active = type
}

const getOrderState = () => {
    uni.$u.http.get('Orders/getOrderState', {
        params: {
            order_no: orderNo.value
        }
    }).then((res: any) => {
        if (res?.code === 200) {
            uni.hideLoading();
            toast(res?.msg ?? '网络错误')
        } else if (res?.code === 500) {
            uni.hideLoading();
            toast(res?.msg ?? '网络错误')
        } else{
            OrderStateNum.value++;
            if (OrderStateNum.value > 10) {
                uni.hideLoading();
                toast(res?.msg ?? '网络错误')
                return;
            }
            setTimeout(getOrderState, 1000)
        }
    })
}

const onBridgeReady = () => {    
    WeixinJSBridge.invoke('getBrandWCPayRequest', payInfo.value, (res: any) => {
        if (res.err_msg == "get_brand_wcpay_request:ok") {
            uni.showLoading({
                title: '查询中...',
                mask: true
            });
            getOrderState();
        }
    });
}

const unifiedOrder = (order_no: string) => {
    orderNo.value = order_no
    const platform = isWeiXinLogin()&&userInfo.value.wechat_openid ? 'wechat' : 'h5';
    const params = {
        platform,
        order_no
    }
    uni.$u.http.post('Orders/unifiedOrder', params).then((res: any) => {
        if (platform === 'wechat') {
            payInfo.value = res?.data
            if (typeof WeixinJSBridge == "undefined") {
                if (document.addEventListener) {
                    document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                } else if (document.attachEvent) {
                    document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                    document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                }
            } else {
                onBridgeReady();
            }
        } else if (res?.data?.pay_url) {
            window.location.href = res.data.pay_url
        } else {
            toast(res?.msg ?? '网络错误')
        }
    });
}

const hanldPay = () => {
    uni.$u.http.post('Orders/created').then((res: any) => {
        if (res?.code == 200) {
            unifiedOrder(res?.data?.order_no);
        } else {
            toast(res?.msg ?? '网络错误')
        }
    });
}
onLoad((e: any) => {
    const index = e?.t ?? 0
    serviceTools.value.active = serviceTools.value.list[index].type
    serviceTools.value.current = index;

})
onShow(() => {
    uni.$emit('user::update')
})
</script>

<style lang="scss" scoped>
.user-container {
    .user-bg-container {
        height: 400rpx;
        background: linear-gradient(to right, var(--theme-color), var(--theme-active-color));
        position: relative;

        .info-block {
            position: absolute;
            bottom: -100rpx;
            left: 30rpx;
            right: 30rpx;
            background: #fff;
            border-radius: 20rpx;
            overflow: hidden;

            .user-box {
                display: flex;
                align-items: center;
                justify-content: center;
                padding: 30rpx 0;

                .userinfo {
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    justify-content: center;

                    .avatar-box {
                        position: relative;
                        background: linear-gradient(to right, var(--theme-color), var(--theme-active-color));
                        border-radius: 50%;
                        padding: 3rpx;
                        overflow: hidden;

                        .avatar {
                            width: 150rpx;
                            height: 150rpx;
                            border-radius: 50%;
                        }

                        .is-level {
                            position: absolute;
                            bottom: 0;
                            left: 0;
                            right: 0;
                            display: flex;
                            justify-content: center;
                            align-items: center;
                            text-align: center;
                            font-weight: 700;

                            .level-icon {
                                width: 39px;
                                height: 10px;
                                background: linear-gradient(181deg, #FED6AD 0%, #FFF1E0 100%);
                                border-radius: 4px 4px 4px 4px;
                                opacity: 1;
                                padding: 3rpx 15rpx 15rpx 15rpx;
                            }
                        }
                    }

                    .info {
                        text-align: center;
                        line-height: 45rpx;
                        padding-top: 10rpx;

                        .nickname {
                            font-size: 32rpx;
                            font-weight: 700;
                        }

                        .level {
                            color: #E7A33D;
                            font-size: 26rpx;
                            display: flex;
                            align-items: center;
                            gap: 5rpx;
                        }
                    }
                }
            }

            .user-account-cash {
                display: flex;
                padding: 0 40rpx;
                background: #fff;
                border-top: 1px solid #E6EBF0;

                .item {
                    flex: 1;
                    text-align: center;
                    padding: 25rpx 0;

                    .num {
                        font-size: 30rpx;
                        padding-top: 10rpx;
                        font-weight: 700;
                    }

                    .text {
                        font-size: 28rpx;
                        color: #888;
                    }
                }
            }
        }
    }

    .dealer-container {
        margin: 130rpx 30rpx 0 30rpx;
        background: linear-gradient(90deg, #FCE9DF 0%, #FFDFD4 100%);
        display: flex;
        justify-content: space-between;
        padding: 20rpx 30rpx;
        border-radius: 20rpx;

        .text-container {
            display: flex;
            align-items: center;

            .text {
                font-size: 28rpx;

                .warning {
                    color: #EF446D;
                }
            }
        }

        .apply-btn {
            border-radius: 30rpx;
            border: 1px solid #B05241;
            padding: 5rpx 20rpx;
            font-size: 24rpx;
            color: #B05241;
            display: flex;
            align-items: center;
        }
    }

    .dealer-close {
        margin-top: 120rpx !important;
    }

    .service-container {
        margin-top: 30rpx;

        .tools-container {
            display: flex;
            gap: 30rpx;
            background: #fff;
            padding: 0 30rpx 30rpx 30rpx;
            margin-top: 20rpx;

            .item {
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                padding-top: 30rpx;
                font-size: 26rpx;

                .text {
                    margin-top: 6rpx;
                }
            }

            .hide {
                display: none !important;
            }
        }

        .vip-container {
            background: #FFFFFF linear-gradient(180deg, #FFE7AB 0%, rgba(255, 231, 171, 0) 100%);
            margin-top: 30rpx;
            padding: 0 30rpx;

            .divider {
                padding-top: 20rpx;
            }

            .desc-vip {
                font-size: 26rpx;
                color: #CE9C27;
                text-align: center;
            }

            .privilege-vip {
                display: flex;
                justify-content: space-between;
                padding: 40rpx 0;

                .item {
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    justify-content: center;

                    .text {
                        color: #666;
                        font-size: 28rpx;
                        padding-top: 10rpx;
                    }
                }
            }

            .unlock-vip {
                padding: 80rpx 0;

                .unlock-btn {
                    background: #F8D488;
                    color: #612C02;
                    text-align: center;
                    padding: 25rpx 0;
                    font-size: 28rpx;
                    border-radius: 40rpx;
                    font-weight: 700;
                }
            }
        }
    }
}</style>